package com.tanhua.server.service;


import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.autoconfig.template.SmsTemplate;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.model.domain.User;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.utils.Constants;
import com.tanhua.utils.JwtUtils;
import io.jsonwebtoken.JwsHeader;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserService {
    @Autowired
    private SmsTemplate smsTemplate;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @DubboReference
    private UserApi userApi;
    @Autowired
    private HuanXinTemplate huanXinTemplate;

//    发送验证码
    public void sendCode(String phone) {
        //1. 生成随机验证码
        //String code = RandomStringUtils.randomNumeric(6);
        String code="123456";

        //2. 调用阿里云发送验证码
        //smsTemplate.sendSms(phone, code);
        //3. 将验证码保存到redis            设置失效时间为5分钟（Duration.ofMinutes(5)）
        redisTemplate.opsForValue().set("CHECK_CODE_" + phone, code, Duration.ofMinutes(5));
    }

/*//    登录校验
    public Map loginVerification(String mobile, String code) {
        //1. 从Redis中获取验证码
        String redisCode = redisTemplate.opsForValue().get("CHECK_CODE_" + mobile);

        //2. 校验验证码
        if(StringUtils.isEmpty(code) || !code.equals(redisCode)) {
            throw new RuntimeException("验证码校验失败");
        }
        //比对通过 , 删除验证码
        redisTemplate.delete("CHECK_CODE_" + mobile);

        //3. 判断用户是否注册
        boolean isNew = false;
        User user = userApi.findByMobile(mobile);
        if (user == null) {
            user = new User();
            user.setMobile(mobile);
            user.setPassword(DigestUtils.md5Hex("123456"));
            Long id = userApi.save(user);
            user.setId(id);
            isNew = true;
        }

        //4. 登录成功, 生成token
        Map<String, Object> tokenMap = new HashMap<String, Object>();
        tokenMap.put("id", user.getId());
        tokenMap.put("mobile", mobile);
        String token = JwtUtils.getToken(tokenMap);

        //5. 封装数据返回
        Map<String, Object> result = new HashMap<>();
        result.put("token", token);
        result.put("isNew", isNew);

        return result;
    }*/

//    注册时注册环信
    public Map loginVerification(String phone,String code){
        //1、从redis中获取下发的验证码
        String redisCode = redisTemplate.opsForValue().get("CHECK_CODE_" + phone);
        //2、对验证码进行校验（验证码是否存在，是否和输入的验证码一致）
        if (StringUtils.isEmpty(redisCode) || !redisCode.equals(code)){
            //验证码无效
            throw new BusinessException(ErrorResult.loginError());
        }
        //3、删除redis中的验证码
        redisTemplate.delete("CHECK_CODE_"+phone);
        //4、通过手机号码查询用户
        User user = userApi.findByMobile(phone);
        Boolean isNsw = false;
        //5、如果用户不存在，创建用户保存到数据库中
        if (user == null){
            user = new User();
            user.setMobile(phone);
            user.setHxPassword(DigestUtils.md5Hex("123"));
            Long save = userApi.save(user);
             isNsw = true;
            //注册环信用户
            String HxUser = "hx"+user.getId();
            Boolean create = huanXinTemplate.createUser(HxUser, Constants.INIT_PASSWORD);
            if (create){
                user.setHxUser(HxUser);
                user.setHxPassword(Constants.INIT_PASSWORD);
                userApi.update(user);
            }
        }
        //6、通过JWT生成token(存入id和手机号码)
        Map tokenMap = new HashMap();
        tokenMap.put("id",user.getId());
        tokenMap.put("mobile",phone);
        String token = JwtUtils.getToken(tokenMap);
        //7、构造返回值
        Map retMap = new HashMap();
        retMap.put("toKen",token);
        retMap.put("isNsw",isNsw);
        return retMap;
    }
}
